import React from "react";
import { modalPropsType } from "@/constants/types";
import { Form, Modal, Space, Row, Col, Input, Button, DatePicker, Radio } from "antd";
import { fetchActivityOptions } from "../../services";
import XlUpload from "@/components/Form/XlUpload";
import { MinusOutlined, PlusOutlined } from "@ant-design/icons";
import { useModel } from "@umijs/max";
import { fetchLpsLineTagOptions } from "@/pages/ProductManage/services";
import { useRequest } from "ahooks";
import XlSelect from "@/components/Form/XlSelect";

const {Item} = Form;
const normFile = (e: any) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};
const labelCol = {span: 8};

const AddAd = ({title, onCancel, onSubmit, loading, visible}: modalPropsType) => {
  const [form] = Form.useForm();
  // const [pages, setPages] = useState([]);
  // const [slots, setSlots] = useState([]);
  const { getDict } = useModel("dictModel");
  const targetType = getDict("targetType");

  const {data: tagOptions} = useRequest(async () => {
    const res = await fetchLpsLineTagOptions({type: '2'});
    return  res || [];
  });
  const {data: activityOptions} = useRequest(fetchActivityOptions);

  const pageId = Form.useWatch("pageId", form);

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit(res?.adList?.map((v: any) => ({
      name: v?.name,
      title: v?.title,
      imageName: v?.image?.[0]?.name,
      imagePath: v?.image?.[0]?.responseUrl,
      targetType: v?.targetType,
      linkTagId: v?.linkTagId,
      linkTagName: tagOptions?.find((op: any) => op?.id === v?.linkTagId)?.name,
      targetPath: v?.targetPath,
      linkActivityId: v?.linkActivityId,
      linkActivityName: activityOptions?.find((op: any) => op?.id === v?.linkActivityId)?.name,
      startTime: v?.time?.[0]?.format('YYYY-MM-DD 00:00:00'),
      endTime: v?.time?.[1]?.format('YYYY-MM-DD 23:59:59')
    })));
  }

  // const currPage: any = useMemo(() => {
  //   if (!pages?.length || !pageId) {
  //     return null;
  //   }
  //   return pages?.find((v: any) => v.value === pageId);
  // }, [pageId, JSON.stringify(pages)])


  // useEffect(() => {
  //   if (pageId) {
  //     fetchAdPageSlotOptions({pageId}).then(
  //       res => {
  //         setSlots((res || [])?.map((v: any) => ({...v, label: v, value: v})))
  //       }
  //     )
  //   } else {
  //     setSlots([]);
  //   }
  // }, [pageId])

  // useComponentDidMount(() => {
  //   fetchAdPageOptions().then(
  //     res => {
  //       setPages((res || []).map((v: any) => ({...v, label: v?.name, value: v?.id})));
  //     }
  //   )
  // });

  
  return (
    <Modal
      title={title}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      open={visible}
      width="750px"
      maskClosable={false}
    >
      <Form form={form} className="modal-form-padding" labelCol={labelCol}>
        {/* <Item label="广告位" labelCol={{span: 2}}>
          <Space>
            <Item noStyle name="pageId">
              <Select options={pages} onChange={() => form.setFieldValue('slot', null)} style={{width: 200}} />
            </Item>
            <Item noStyle name="slot">
              <Select options={slots} style={{width: 200}} />
            </Item>
          </Space>
        </Item> */}
        <Row gutter={30}>
          <Col span={24}>
            <Form.List name="adList" initialValue={[{}]}>
              {(fields, {add, remove}) =>
                fields.map((field, fieldIndex) => (
                  <Space style={{marginTop: 30}}>
                    <div style={{width: '550px'}}>
                      <Item label="广告图" rules={[{required: true, message: '请上传广告图'}]} name={[field.name, "image"]} getValueFromEvent={normFile}>
                        <XlUpload accept=".jpeg,.png,.jpg" max={1} listType="picture-card" uploadParams={{businessCode: 'ad'}} />
                      </Item>
                      <Item label="广告名称" name={[field.name, "name"]} rules={[{required: true, message: '请输入广告名称'}]}>
                        <Input maxLength={20} />
                      </Item>
                      <Item label="广告标题" name={[field.name, "title"]} rules={[{required: true, message: '请输入广告标题'}]}>
                        <Input maxLength={20} />
                      </Item>
                      <Item label="跳转" name={[field.name, "targetType"]} rules={[{required: true, message: '请选择落地页类型'}]}>
                        <Radio.Group options={targetType} />
                      </Item>
                      <Item noStyle shouldUpdate>
                        {({getFieldValue}) => {
                          const value = getFieldValue(['adList', field.name, 'targetType']);
                          return (
                            <Item label="关联标签" name={[field.name, "linkTagId"]} rules={value === '2' ? [{required: true, message: '请选择关联标签'}] : undefined}>
                              <XlSelect allowClear showSearch optionFilterProp="label" options={tagOptions} dataLabel="name" dataValue="id" />
                            </Item>
                          );
                        }}
                      </Item>
                      <Item noStyle shouldUpdate>
                        {({getFieldValue}) => {
                          const value = getFieldValue(['adList', field.name, 'targetType']);
                          return (
                            <Item label="链接地址" name={[field.name, "targetPath"]} rules={value === '3' ? undefined : [{required: true, message: '请输入链接地址'}]}>
                              <Input />
                            </Item>
                          );
                        }}
                      </Item>
                      <Item noStyle shouldUpdate>
                        {({getFieldValue}) => {
                          const value = getFieldValue(['adList', field.name, 'targetType']);
                          return (
                            <Item label="关联活动" name={[field.name, "linkActivityId"]} rules={value === '3' ? [{required: true, message: '请选择关联活动'}] : undefined}>
                              <XlSelect showSearch  optionFilterProp="label"  allowClear options={activityOptions} dataLabel="name" dataValue="id" />
                            </Item>
                          );
                        }}
                      </Item>
                      <Item label="投放时间" name={[field.name, "time"]} rules={[{required: true, message: '请选择投放时间'}]}>
                        <DatePicker.RangePicker />
                      </Item>
                    </div>
                    <div>
                      {fieldIndex === 0 && <Button type="primary" onClick={() => add({})}><PlusOutlined /></Button>}
                      {fieldIndex > 0 && <Button type="primary" onClick={() => remove(field.name)}><MinusOutlined /></Button>}
                    </div>
                  </Space>
                ))
              }
            </Form.List>
          </Col>
          {/* <Col span={12}>
            {currPage && (
              <Image src={currPage?.imageUrl} width={375} height={667} />
            )}
          </Col> */}
        </Row>
      </Form>
    </Modal>
  );
}
export default AddAd;